package com.shuqi.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.EditTextLengthFilter;
import com.shuqi.application.PasswordProcess;
import com.shuqi.common.utils.RegexUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.MainController;
import com.shuqi.controller.PasswordModifyController;
import com.shuqi.controller.R;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.manager.MyAccountManager;

/**
 * 修改密码界面
 * 
 * @author liyizhe
 */
public class PasswordModifyActivity extends ActivityBase implements OnClickListener,
        OnFocusChangeListener, IEventListener{

    private PasswordModifyController controller;
    private EditText EditOldPassword = null;
    private EditText EditNewPassword = null;
    private ImageView ImgOldVisible = null;
    private ImageView ImgNewVisible = null;
    private TextView ModifyOk = null;

    /**
     * 密码是否可见图标
     */
    private int iOldVisible;
    private int iNewVisible;

    /** 修改结果提示语 */
    private String result;
    private String err;// 连网错误提示
    private ProgressDialog pdialog;
    private CommonTitle mTitle;
    private final int INIT = EventTypeConstants.BASE;
    private final int SAVEDETAILS = INIT + 1;
    private final int INITSUCCESS = SAVEDETAILS + 1;
    private final int NETERROR = INITSUCCESS + 1;

    List<BasicNameValuePair> params;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    break;
                case SAVEDETAILS:
                    activityInitData();
                    break;
                case INITSUCCESS:
                    afterSave();
                    break;
                case NETERROR:
                    if (!TextUtils.isEmpty(err)) {
                        showMsg(err);
                        err = null;
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.controller =
                (PasswordModifyController) MainController.getMainManagerInstance()
                        .createController(MainController.CONTROLLER_ID_PASSWORDMODIFY, this);
        this.controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.act_account_passwordmodify);
        handler.sendEmptyMessage(INIT);
    }

    @Override
    public void onEvent(int event, Object data) {

        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                // 读取数据 写处理逻辑
                result = (String) data;
                handler.sendEmptyMessage(INITSUCCESS);
                break;
            case EventTypeConstants.EVENT_EXC_IO_2:
                err = "请联网..";
                handler.sendEmptyMessage(NETERROR);
                break;
            default:
                err = "请联网..";
                handler.sendEmptyMessage(NETERROR);
                break;
        }

        try {
            if (pdialog.isShowing()) {
                pdialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void activityLogicForward() {
        iOldVisible = 1;
        iNewVisible = 1;

        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        EditOldPassword = (EditText) findViewById(R.id.edit_old_password);
        EditNewPassword = (EditText) findViewById(R.id.edit_new_password);
        ImgOldVisible = (ImageView) findViewById(R.id.img_old_visible);
        ImgNewVisible = (ImageView) findViewById(R.id.img_new_visible);
        ModifyOk = (TextView) findViewById(R.id.modify_ok);

        ImgOldVisible.setOnClickListener(this);
        ImgNewVisible.setOnClickListener(this);
        ModifyOk.setOnClickListener(this);
        EditOldPassword.setOnFocusChangeListener(this);
        ImgNewVisible.setOnFocusChangeListener(this);

        InputFilter[] filters = {new EditTextLengthFilter(16)};
        EditOldPassword.setFilters(filters);
        EditNewPassword.setFilters(filters);
    }

    @Override
    public void activityInitData() {
        if (pdialog == null) {
            pdialog = new ProgressDialog(this);
            pdialog.setMessage("正在修改密码");
        }
        pdialog.show();

        params = setParams();
        controller.handle(0, params);
    }

    /**
     * @Des 描述 获取接口组织参数
     * @return List<BasicNameValuePair>
     */
    public List<BasicNameValuePair> setParams() {
        List<BasicNameValuePair> pwParams = new ArrayList<BasicNameValuePair>();
        String str_old_psw = EditOldPassword.getText().toString().trim();
        String str_new_psw = EditNewPassword.getText().toString().trim();

        String old_psw = PasswordProcess.getLgPassword(str_old_psw);
        String new_psw = PasswordProcess.getLgPassword(str_new_psw);

        UserInfo userInfo = MyAccountManager.getInstance(PasswordModifyActivity.this);
        pwParams.add(new BasicNameValuePair("userid", userInfo.getUserId()));// 用户id
        pwParams.add(new BasicNameValuePair("pwd_old", old_psw));
        pwParams.add(new BasicNameValuePair("pwd_new", new_psw));
        String key = "c56cf32e9a52a265ae47cd50570266cc";

        long timestamp = System.currentTimeMillis();
        String strTimestamp = timestamp + "";
        String md5_key_sb = key + timestamp;
        String md5_key = Util.MD5(md5_key_sb.toString());
        pwParams.add(new BasicNameValuePair("key", md5_key));// md5
        pwParams.add(new BasicNameValuePair("timestamp", strTimestamp));// 时间戳

        return pwParams;
    }

    /**
     * 提交修改资料的连网结束后的操作
     */
    public void afterSave() {
        if (!TextUtils.isEmpty(result)) {
            Toast.makeText(PasswordModifyActivity.this, result, Toast.LENGTH_LONG).show();
            if (result.contains("成功")) {
                UserInfo userInfo = MyAccountManager.getInstance(PasswordModifyActivity.this);

                String new_psw = EditNewPassword.getText().toString().trim();
                userInfo.setPassword(new_psw);
                setResult(Activity.RESULT_OK);
                finish();
            }
            result = null;
        } else {
            err = getResources().getString(R.string.err_empty_bookskeyword);
            showMsg(err);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                this.finish();
                break;
            case R.id.img_old_visible: {
                if (iOldVisible == 1) {
                    iOldVisible = 0;
                    ImgOldVisible.setImageResource(R.drawable.password_invisible);
                    //EditOldPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    int start = EditOldPassword.getSelectionStart();
                    EditOldPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    changeEditSelection(EditOldPassword,start);
                } else {
                    iOldVisible = 1;
                    ImgOldVisible.setImageResource(R.drawable.password_visible);
                    //EditOldPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    int start = EditOldPassword.getSelectionStart();
                    EditOldPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    changeEditSelection(EditOldPassword,start);
                }
                break;
            }
            case R.id.img_new_visible: {
                if (iNewVisible == 1) {
                    iNewVisible = 0;
                    ImgNewVisible.setImageResource(R.drawable.password_invisible);
                    //EditNewPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    int start = EditNewPassword.getSelectionStart();
                    EditNewPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    changeEditSelection(EditNewPassword,start);
                } else {
                    iNewVisible = 1;
                    ImgNewVisible.setImageResource(R.drawable.password_visible);
                    //EditNewPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    int start = EditNewPassword.getSelectionStart();
                    EditNewPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    changeEditSelection(EditNewPassword,start);
                }
                break;
            }
            case R.id.modify_ok: {
                String old_psw = EditOldPassword.getText().toString().trim();
                String new_psw = EditNewPassword.getText().toString().trim();

                if (TextUtils.isEmpty(old_psw) || TextUtils.isEmpty(new_psw)) {
                    showMsg("没填密码呀");
                }else if(!RegexUtil.isPassword(new_psw)){
                    showMsg("请输入6-16位字母或数字");
                }else if (new_psw.length() < 6) {
                    showMsg("密码过短，请输入6-16位新密码");
                } else if (new_psw.length() > 16) {
                    showMsg("密码过长，请输入6-16位新密码");
                } else {
                    handler.sendEmptyMessage(SAVEDETAILS);
                }
                break;
            }
        }
    }
    private void changeEditSelection(EditText editText , int start){
        if(start<0 || start>editText.getText().length()){
            start = editText.getText().length();
        }
        editText.setSelection(start);
    }

    /**
     * 输入框焦点改变，背景改变
     */
    @Override
    public void onFocusChange(View view, boolean hasFocus) {

        if (view.getId() == R.id.edit_old_password) {
            if (hasFocus) {
                ((RelativeLayout) findViewById(R.id.layout_old))
                        .setBackgroundResource(R.drawable.input_box_f);
                ((RelativeLayout) findViewById(R.id.layout_new))
                        .setBackgroundResource(R.drawable.input_box_n);
            } else {
                ((RelativeLayout) findViewById(R.id.layout_old))
                        .setBackgroundResource(R.drawable.input_box_n);
                ((RelativeLayout) findViewById(R.id.layout_new))
                        .setBackgroundResource(R.drawable.input_box_f);
            }
        }
    }

    /**
     * 屏幕触摸事件,消失软键盘
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm =
                (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(EditOldPassword.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(EditNewPassword.getWindowToken(), 0);

        return super.onTouchEvent(event);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
